﻿#include "Tree.h"

Tree* MakeSpace(TDatatype x)
{
	Tree* tmp = (Tree*)malloc(sizeof(Tree));
	if (tmp == NULL)
	{
		perror("tmp fail !\n");
		exit(1);
	}
	tmp->data = x;
	tmp->left = tmp->right = NULL;
	return tmp;
}

//根左右
void PreOrder(Tree* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	printf("%c ", root->data);
	PreOrder(root->left);
	PreOrder(root->right);
}

//左根右
void MinOrder(Tree* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	MinOrder(root->left);
	printf("%c ", root->data);
	MinOrder(root->right);
}

//左右根
void PosOrder(Tree* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	PosOrder(root->left);
	PosOrder(root->right);
	printf("%c ", root->data);
}

//二叉树结点个数
int BinaryTreeSize(Tree* root)
{
	if (root == NULL)
	{
		return 0;
	}
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}

//二叉树叶子结点个数
int BinaryTreeLeafSize(Tree* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}

// ⼆叉树第k层结点个数
int BinaryTreeLevelKSize(Tree* root, int k)
{
	if (root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->left,k-1) + BinaryTreeLevelKSize(root->right,k-1);
}

//⼆叉树的深度/⾼度
int BinaryTreeDepth(Tree* root)
{
	if (root == NULL)
	{
		return 0;
	}
	int leftDep = BinaryTreeDepth(root->left);
	int rightDep = BinaryTreeDepth(root->right);
	return 1 + (leftDep < rightDep ? rightDep : rightDep);
}

// ⼆叉树查找值为x的结点
Tree* BinaryTreeFind(Tree* root, TDatatype x)
{
	if (root == NULL)
	{
		return NULL;
	}
	if (root->data == x)
	{
		return root;
	}
	Tree* leftDdata = BinaryTreeFind(root->left,x);
	Tree* rightDdata = BinaryTreeFind(root->right,x);
	if (leftDdata)
	{
		return leftDdata;
	}
	if (rightDdata)
	{
		return rightDdata;
	}
	return NULL;
}

// ⼆叉树销毁
void BinaryTreeDestory(Tree** root)
{
	if (*root == NULL)
	{
		return;
	}
	BinaryTreeDestory(&(*root)->left);
	BinaryTreeDestory(&(*root)->right);
	free(*root);
	*root = NULL;
}